package com.ruantu.clothing.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruantu.clothing.dao.*;
import com.ruantu.clothing.entity.*;
import com.ruantu.clothing.entity.finance.FinanceRecord;
import com.ruantu.clothing.entity.report.ChuKuReport;
import com.ruantu.clothing.entity.report.Foot;
import com.ruantu.clothing.service.ChuKuService;
import com.ruantu.clothing.service.finance.FinanceService;
import com.ruantu.clothing.util.Chinese;
import com.ruantu.clothing.util.MyException;
import com.ruantu.clothing.util.UUIDUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Footer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * Created by Administrator on 2018/7/9 0009.
 */

@Service
@Transactional
public class ChuKuServiceImpl implements ChuKuService {

    @Autowired
    private ChuKuDao ckDao;

    @Autowired
    private ProductionDetailsMapper pdDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private StoreMapper storeDao;

    @Autowired
    private RukuMapper rukuMapper;

    @Autowired
    private RukusonMapper rukusonMapper;

    @Autowired
    private VipMapper vipMapper;


    @Autowired
    private TuihuoMapper tuihuoMapper;

    @Autowired
    private FinanceService financeService;

    /***
     * 添加出库单
     * @param ck
     * @return
     */
    @Override
    public int addChuKu(User u, ChuKu ck, String chukusonString) {

        if (ck.getId() != null && !"".equals(ck.getId())) {
            Map<String, Object> mapC = new HashMap<>();
            mapC.put("jgId", u.getJgid());
            mapC.put("chukuId", ck.getId());
            Integer chukuState = ckDao.selectOneChuKuDan(mapC);
            if (chukuState == 0) {
                ckDao.deleteChuKuSon(ck.getId());
                ck.setUpdateren(u.getId());
                ck.setUpdateshijian(new Date());
                ckDao.updateChuKuDan(ck);
                if (ck.getFenlei() == 1 || ck.getFenlei() == 2) {
                    Ruku th = new Ruku();
                    th.setId(ck.getId());
                    tuihuoMapper.delTuihuo(th);
                }

            } else {
                throw new MyException("不是草稿状态，不可修改!");
            }

        } else {//新增
            ck.setId(UUIDUtil.getUUID());
            ck.setZhidanshijian(new Date());
            ck.setState(0);//0为新单
            int hashCodeV = UUID.randomUUID().toString().hashCode();
            if (hashCodeV < 0) {//有可能是负数
                hashCodeV = -hashCodeV;
            }
            ck.setChukudanhao("CK" + ck.getChukuleixing() + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+String.format("%011d", hashCodeV));
            ckDao.addChuKu(ck);//存出库主表
        }

        List<ChuKuSon> list = new ArrayList<>();//保存rukusonshuju
        JSONArray obj = JSONArray.parseArray(chukusonString);
        ProductionDetails pd = new ProductionDetails();

        if (ck.getFenlei() == 1 || ck.getFenlei() == 2) {
            List<Tuihuo> listTH = new ArrayList<>();
            for (int i = 0; i < ck.getChukuIdArray().length; i++) {
                Tuihuo th = new Tuihuo();
                th.setDanjuId(ck.getChukuIdArray()[i]);
                th.setTuihuoId(ck.getId());
                th.setId(UUIDUtil.getUUID());
                listTH.add(th);
            }
            tuihuoMapper.insertList(listTH);
        }
        for (int i = 0; i < obj.size(); i++) {
            JSONObject jo = (JSONObject) obj.get(i);
            pd.setProductionId(jo.getString("productoinId"));
            pd.setColor(jo.getString("color"));
            pd.setSize(jo.getString("size"));
            String productDetails = pdDao.findIdBy(pd);
            if (productDetails != null) {
                if (ck.getFenlei() == 0) {
                    list.add(new ChuKuSon(
                            UUIDUtil.getUUID(),
                            productDetails,
                            Integer.parseInt(jo.getString("shuliang")) * -1,
                            Double.parseDouble(jo.getString("danjia")),
                            ck.getId()));
                } else if (ck.getFenlei() == 1 || ck.getFenlei() == 2) {
                    list.add(new ChuKuSon(
                            UUIDUtil.getUUID(),
                            productDetails,
                            Integer.parseInt(jo.getString("shuliang")),
                            Double.parseDouble(jo.getString("danjia")),
                            ck.getId()));
                }
            } else {
                throw new MyException("数据异常!");
            }
        }
        ckDao.addChuKuSon(list);

        return 0;
    }

    /***
     *  获得出库列表
     * @param ck
     * @return
     */
    @Override
    public List<ChuKu> findAllChuKuList(ChuKu ck, PageBean page) {
        List<User> userList = userDao.selectAllUser();
        Map<String, Object> mapCan = new HashMap<>();
        mapCan.put("state", ck.getState());
        mapCan.put("stateB", ck.getStateB());
        mapCan.put("stateC", ck.getStateC());
        mapCan.put("stateD", ck.getStateD());
        mapCan.put("jgId", ck.getJgId());
        if (ck.getWldwName() != null && ck.getWldwName() != "") {
            if (new Chinese().isChinese(ck.getWldwName())) {
                mapCan.put("type", 0);
            } else {
                mapCan.put("type", 1);
            }
        }
        mapCan.put("key", ck.getWldwName());
        mapCan.put("chukuleixing", ck.getChukuleixing());
        mapCan.put("fenlei", ck.getFenlei());
        mapCan.put("start", page.getStart());
        mapCan.put("pageSize", page.getRows());
        mapCan.put("stime", ck.getQtime());
        mapCan.put("etime", ck.getEtime());
        List<ChuKu> chukuList = ckDao.selectChuKuDan(mapCan);

        if (chukuList != null && userList != null) {
            for (int i = 0; i < userList.size(); i++) {
                for (int j = 0; j < chukuList.size(); j++) {
                    if (chukuList.get(j).getZhidanren() != null && chukuList.get(j).getZhidanren() == userList.get(i).getId()) {
                        chukuList.get(j).setZhidanrenName(userList.get(i).getNikeName());
                    }
                    if (chukuList.get(j).getBohuiren() != null && chukuList.get(j).getBohuiren() == userList.get(i).getId()) {

                        chukuList.get(j).setBohuirenName(userList.get(i).getNikeName());
                    }
                    if (chukuList.get(j).getChukuren() != null && chukuList.get(j).getChukuren() == userList.get(i).getId()) {
                        chukuList.get(j).setChukurenName(userList.get(i).getNikeName());
                    }
                    if (chukuList.get(j).getShenheren() != null && chukuList.get(j).getShenheren() == userList.get(i).getId()) {

                        chukuList.get(j).setShenherenName(userList.get(i).getNikeName());
                    }
                    if (chukuList.get(j).getTongguoren() != null && chukuList.get(j).getTongguoren() == userList.get(i).getId()) {

                        chukuList.get(j).setTongguorenName(userList.get(i).getNikeName());
                    }

                }

            }

        }
        Foot foot=ckDao.selectChuKuCount(mapCan);
                if(foot!=null){
                    foot.setProduct("总计:");
                }
        page.setFoot(foot);
        return chukuList;
    }

    /***
     * 获得出库单子表信息
     * @param chukuId
     * @param
     * @return
     */
    @Override
    public List<DanPro> selectAllChuKuSonForCHuKuIdService(String chukuId, int type) {

        Map<String, Object> mapCan = new HashMap<>();
        mapCan.put("chukuId", chukuId);
        mapCan.put("type", type);
        return ckDao.selectAllChuKuSonForCHuKuId(mapCan);
    }

    /***
     * 更新出库状态
     * @param
     * @return
     */
    @Override
    public Integer updateStateService(Integer state, String beizhu, User u, String chukuId) {
        Map<String, Object> mapCan = new HashMap<>();
        mapCan.put("jgId", u.getJgid());
        mapCan.put("state", state);
        mapCan.put("shijian", new Date());
        mapCan.put("ren", u.getId());
        mapCan.put("beizhu", beizhu);
        mapCan.put("chukuId", chukuId);
        Integer chukuid = ckDao.selectOneChuKuDan(mapCan);
        if (chukuId != null) {
            if (state == 1) {
                if (chukuid != 0) {
                    throw new MyException("该单不是草稿状态!");
                }
            } else if (state == 2) {
                if (chukuid != 1) {
                    throw new MyException("该单不是待审核状态!");
                }
            } else if (state == 3) {
                if (chukuid != 2) {
                    throw new MyException("该单不是已审核状态!");
                }
            } else if (state == 0) {

                if (chukuid == 3 || chukuid == 0) {

                    throw new MyException("该单不是待审核或已审核状态，不可驳回");
                }
            }
        }
        ckDao.updateState(mapCan);

        return 0;
    }

    /***
     * 删除出库单
     * @param chukuId
     * @param u
     * @return
     */
    @Override
    public Integer delChuKu(String chukuId, User u) {
        Map<String, Object> mapCan = new HashMap<>();
        mapCan.put("jgId", u.getJgid());
        mapCan.put("chukuId", chukuId);
        Integer chukuid = ckDao.selectOneChuKuDan(mapCan);
        if (chukuid != null) {
            if (chukuid == 0) {
                Ruku rk = new Ruku();
                rk.setId(chukuId);
                ckDao.deleteChuKuDan(chukuId);
                ckDao.deleteChuKuSon(chukuId);
                tuihuoMapper.delTuihuo(rk);
            } else {
                throw new MyException("不是草稿状态，不可删除!");
            }
        } else {
            throw new MyException("数据异常!");
        }

        return 0;
    }


    /***
     * 出库修改
     * @param chukuId
     * @return
     */
    @Override
    public List<ChuKu> xiugaiChuKuService(String chukuId, User u) {
        Map<String, Object> mapCan = new HashMap<>();
        mapCan.put("jgId", u.getJgid());
        mapCan.put("chukuId", chukuId);
        Integer chukuid = ckDao.selectOneChuKuDan(mapCan);
        List<ChuKu> li = null;
        List<ProSon> chukusum = null;
        List<ChuKuSonXiu> lison = null;
        if (chukuid == 0) {
            li = ckDao.xiugaiChuKu(chukuId);
            lison = ckDao.xiugaiChuKuSon(chukuId);
            for (int i = 0; i < li.size(); i++) {
                for (int j = 0; j < lison.size(); j++) {
                    if (li != null && lison != null) {
                        if (li.get(i).getId().equals(lison.get(j).getChukuId())) {
                            li.get(i).getChukuson().add(lison.get(j));
                        }

                    }
                }
            }
        } else {
            throw new MyException("不是草稿状态不可修改!");
        }
        return li;
    }


    /***
     * 出库更改库存
     * @param u
     * @param chukuId
     * @return
     */
    @Override
    public Integer ChuKu(User u, String chukuId) {

        List<Store> chukusonList = ckDao.selectAllChuKuSon(chukuId);//获得当前出库单
        if (chukusonList.get(0).getState() != 2) {//判断是不是已审核的单子，只有审核的单子可出库

            throw new MyException("不是已审核状态，不可出库!");
        }

        //分销出库生成入库单
        List<Rukuson> list = new ArrayList<>();//分销生成出库单子信息
        Ruku ruku = new Ruku();//分销生成入库单
        if (chukusonList.get(0).getChukuleixing() == 1 && chukusonList.get(0).getLeixing() == 0) {//leixing为销售（0）或销售退货（1<正品退货>，2<次品退货>）
            ruku.setId(UUIDUtil.getUUID());
            ruku.setZhidanren(u.getId());
            ruku.setZhidanshijian(new Date());
            ruku.setFenlei(0);
            ruku.setJgId(chukusonList.get(0).getWldw());
            ruku.setGongyingshangid(chukusonList.get(0).getJgId());
            ruku.setRukuleixing(2);
            ruku.setState(0);
            ruku.setRukudanhao("RK" + ruku.getRukuleixing() + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
            rukuMapper.insertRuku(ruku);
        }
        //结束

        List<Store> addStore = new ArrayList<>();//存库存没有数据
        List<Store> upDateStore = new ArrayList<>();//存库存有数据
        Map<String, Object> mapCan = new HashMap<>();
        for (int i = 0; i < chukusonList.size(); i++) {
            if (chukusonList.get(i).getLeixing() == 2) {//判断是否为次品仓数据（1）正仓为（0）判断如果该单是退货单时，赋值为1，改正品仓库存判断如果该单是退货单（2为次品退货单）时，赋值为1，改正品仓库存
                chukusonList.get(i).setLeixing(1);
            } else if (chukusonList.get(i).getLeixing() == 1) {//判断如果该单是退货单（1为退货单）时，赋值为1，改正品仓库存
                chukusonList.get(i).setLeixing(0);
            }
            mapCan.put("productionDetailsId", chukusonList.get(i).getProductionDetailsId());
            mapCan.put("jgId", chukusonList.get(i).getJgId());
            mapCan.put("leixing", chukusonList.get(i).getLeixing());
            if (storeDao.selectStoreSFCZ(mapCan) > 0) {//判断库存里有无该商品
                chukusonList.get(i).setId(UUIDUtil.getUUID());
                upDateStore.add(chukusonList.get(i));

            } else {
                chukusonList.get(i).setId(UUIDUtil.getUUID());
                addStore.add(chukusonList.get(i));
            }
            //分销出库生成入库子单数据
            if (chukusonList.get(0).getChukuleixing() == 1 && chukusonList.get(0).getLeixing() == 0) {
                Rukuson rukuson = new Rukuson();
                rukuson.setId(UUIDUtil.getUUID());
                rukuson.setShuliang(chukusonList.get(i).getShuliang() * -1);
                rukuson.setDanjia(chukusonList.get(i).getDanjia());
                rukuson.setRukuId(ruku.getId());
                rukuson.setProductionDetailsId(chukusonList.get(i).getProductionDetailsId());
                list.add(rukuson);

            }
            //结束
        }
        //财务
        ChuKu SumAndZJ = ckDao.selectAllSumAndZJ(chukuId);
        FinanceRecord recordRu = new FinanceRecord();
        if (SumAndZJ != null) {
            if (SumAndZJ.getFenlei() == 0) {//销售
                recordRu.setAmount(SumAndZJ.getZongjia());
                recordRu.setShuliang(SumAndZJ.getZshuliang());
                recordRu.setGsjg(SumAndZJ.getJgId());
                recordRu.setWldw(SumAndZJ.getWanglaidanwei());
                recordRu.setYddid(SumAndZJ.getChukudanhao());
                recordRu.setFslx("销售");
                recordRu.setHl("" + (-1));
                recordRu.setYearandseason(SumAndZJ.getYearandseason());
                recordRu.setTime(new Date());
                recordRu.setWldwType(1);//销售为1；入库为0
            } else if (SumAndZJ.getFenlei() == 1 || SumAndZJ.getFenlei() == 2) {//销售退货
                recordRu.setAmount(SumAndZJ.getZongjia()*-1);
                recordRu.setShuliang(SumAndZJ.getZshuliang());
                recordRu.setGsjg(SumAndZJ.getJgId());
                recordRu.setWldw(SumAndZJ.getWanglaidanwei());
                recordRu.setYddid(SumAndZJ.getChukudanhao());
                recordRu.setYearandseason(SumAndZJ.getYearandseason());
                recordRu.setFslx("销售退货");
                if (SumAndZJ.getFenlei() == 1) {
                    recordRu.setMark("正品退货");
                } else if (SumAndZJ.getFenlei() == 1) {
                    recordRu.setMark("次品退货");
                }
                recordRu.setHl("" + (1));
                recordRu.setTime(new Date());
                recordRu.setWldwType(1);
            }
            financeService.addFinanceRecord(recordRu);
        } else {

            throw new MyException("数据异常，请联系管理员!");
        }

        //财务结束
        if (addStore != null && addStore.size() != 0) {

            storeDao.insertStoreSome(addStore);
        }

        if (upDateStore != null && upDateStore.size() != 0) {

            storeDao.updateShuliang(upDateStore);
        }

        if (list != null && list.size() != 0) {

            rukusonMapper.insertRukusonSome(list);
        }

        mapCan.put("state", 3);
        mapCan.put("shijian", new Date());
        mapCan.put("ren", u.getId());
        mapCan.put("chukuId", chukuId);
        ckDao.updateState(mapCan);

        return 0;
    }

    @Override
    @Transactional
    public int saveLingshou(ChuKu chuKu, String a) {
        String dh = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        //设置出库单号
        chuKu.setChukudanhao( dh + Math.round(Math.random() * 9 + 1));
        //设置id
        chuKu.setId(UUIDUtil.getUUID());
        //保存出库单
        int code = ckDao.addLingshou(chuKu);
        if (code <= 0) {
            throw new RuntimeException("出库失败，请检查数据重新尝试");
        }
        //批量插入子表
        JSONArray obj = JSONArray.parseArray(a);// 解析String 成JSONARRy
        List<ChuKuSon> chuKuSons = new ArrayList<>();
        double zongjia = 0;
        for (int i = 0; i < obj.size(); i++) {
            JSONObject jo = (JSONObject) obj.get(i);
            ChuKuSon chuKuSon = new ChuKuSon();
            chuKuSon.setId(UUIDUtil.getUUID());
            chuKuSon.setChukuId(chuKu.getId());
            chuKuSon.setDanjia(Double.parseDouble(jo.get("danjia").toString()));
            chuKuSon.setShuliang(Integer.parseInt(jo.get("shuliang").toString()) * -1);
            chuKuSon.setProductDetailsId(jo.get("productDetailsId").toString());
            chuKuSons.add(chuKuSon);
            zongjia += chuKuSon.getDanjia() * chuKuSon.getShuliang();
        }


        //批量插入子表
        code = ckDao.addChuKuSon(chuKuSons);
        if (code <= 0) {
            throw new RuntimeException("出库失败，请检查数据重新尝试");
        }
        // 判断是否是会员是会员就去查询余额，余额够就去更新余额，不够就去让他充值
        if ("-1".equals(chuKu.getWanglaidanwei()) || 0 == chuKu.getZhifu()) {//当为匿名或者会员现金支付时

        } else {//会员卡支付
            Vip vips = new Vip();
            vips.setId(chuKu.getWanglaidanwei());
            //查询会员余额
            Vip balance = vipMapper.findVipById(vips);
            if (balance.getBalance() < Math.abs(zongjia)) {
                throw new RuntimeException("余额不足，请充值后进行尝试");
            } else {
                //新增消费记录
                vips.setCzmoney(zongjia);
                vips.setJifen(Math.abs((int) zongjia));
                vips.setYue(Math.abs(zongjia));
                vips.setLeixing(1);
                vips.setCreateBy(chuKu.getZhidanren());
                code = vipMapper.insertRecord(vips);
                vips.setBalance(zongjia);
                if (code < 0) {
                    throw new MyException("操作失败，内部服务器错误");
                }
                //更新余额
                code = vipMapper.updateBlanceById(vips);
                if (code <= 0) {
                    throw new MyException("操作失败，内部服务器错误");
                }
            }
        }
        List<Store> stores = new ArrayList<>();
        //更新库存
        for (int i = 0; i < chuKuSons.size(); i++) {
            Store store = new Store();
            store.setShuliang(chuKuSons.get(i).getShuliang());
            store.setProductionDetailsId(chuKuSons.get(i).getProductDetailsId());
            store.setJgId(chuKu.getJgId());
            store.setLeixing(0);
            stores.add(store);
        }
        code = storeDao.updateShuliang(stores);
        if (code <= 0) {
            throw new MyException("操作失败，内部服务器错误");
        }
        //TODO 财务
        if (chuKu.getFenlei() == 0) {
            FinanceRecord recordRu = new FinanceRecord();
            recordRu.setAmount(Math.abs(zongjia));
            recordRu.setGsjg(chuKu.getJgId());
            recordRu.setWldw(chuKu.getWanglaidanwei());
            recordRu.setYddid(chuKu.getChukudanhao());
            recordRu.setFslx("零售");
            recordRu.setHl("" + (-1));
            recordRu.setTime(new Date());
            recordRu.setWldwType(1);//销售为1；进货为0
            financeService.addFinanceRecord(recordRu);
        }


        return code;
    }

    /***
     * 获得已完成的出库单退货用
     * @param
     * @return
     */
    @Override
    public List<ChuKu> selectChuKuDan(String kehuId, String productId) {
        Map<String, Object> mapCan = new HashMap<>();
        mapCan.put("kehuId", kehuId);
        mapCan.put("productId", productId);
        List<ChuKu> ckList = ckDao.selectChuKuDanT(mapCan);//获得已出库单
        List<ChuKuSonXiu> cksList = ckDao.selectAllChuKuSonForkehuId(mapCan);//销售但获取:退货用，应退货数
        if (ckList != null && cksList != null && ckList.size() != 0 && cksList.size() != 0) {
            for (int i = 0; i < ckList.size(); i++) {
                for (int j = 0; j < cksList.size(); j++) {
                    if (ckList.get(i).getId().equals(cksList.get(j).getChukuId())) {
                        ckList.get(i).getChukuson().add(cksList.get(j));
                    }
                }
            }
        }
        return ckList;
    }

    @Override
    public List<ChuKu> findSaleList(ChuKu chuKu, String startTime, String endTime, Integer findStyle, PageBean pageBean) {
        Map<String, Object> map = new HashMap<>();
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        map.put("start", pageBean.getStart());
        map.put("rows", pageBean.getRows());
        map.put("findStyle", findStyle);
        map.put("jgId", chuKu.getJgId());
        if (StringUtils.isNotBlank(chuKu.getChukudanhao())) {
            map.put("key", chuKu.getChukudanhao());
        }
        if (chuKu.getFenlei() != -1) {
            map.put("fenlei", chuKu.getFenlei());
        }
        pageBean.setTotal(ckDao.findSaleListCount(map));
        return ckDao.findSaleList(map);
    }

    @Override
    public List<Sale> findSaleById(String id) {
        return ckDao.findSaleById(id);
    }

    @Override
    public List<Sale> findTuihuo(String id) {
        //根据出库id查询全部的可退商品
        List<Sale> list = ckDao.findSaleById(id);
        //根据出库id查询已经退货编号以及数量
        List<Sale> yituihuo = ckDao.findYituihuo(id);
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < yituihuo.size(); j++) {
                //如果产品子表相等
                if (list.get(i).getProductionDetailsId().equals(yituihuo.get(j).getProductionDetailsId())) {
                    //如果退货的数量已经比可退数量大那就移除
                    if (Math.abs(list.get(i).getShuliang()) == Math.abs(yituihuo.get(j).getShuliang())) {
                        //移除该商品
                        list.remove(i);
                        --i;
                        break;
                    }
                }
            }
        }
        return list;
    }

    @Override
    public Sale findTuiHuoByProductionDetailsIdWithProductCode(Sale sale) {
        Sale sales = ckDao.findTuiHuoByProductionDetailsIdWithProductCode(sale);
        sales.setKetuishuliang(sales.getShuliang());
        //根据出库id查询已经退货编号以及数量
        List<Sale> yituihuo = ckDao.findYituihuo(sale.getId());
        for (int i = 0; i < yituihuo.size(); i++) {
            if (yituihuo.get(i).getProductionDetailsId().equals(sales.getProductionDetailsId())) {
                sales.setKetuishuliang(Math.abs(sales.getShuliang()) - Math.abs(yituihuo.get(i).getShuliang()));
                break;
            }
        }
        return sales;
    }

    @Override
    @Transactional
    public int saveTuihuo(ChuKu chuKu, String danjuId, String a) {
        String dh = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        //设置出库单号
        chuKu.setChukudanhao(chuKu.getJgId() + dh + Math.round(Math.random() * 9 + 1));
        //设置id
        chuKu.setId(UUIDUtil.getUUID());
        //保存出库单
        int code = ckDao.addLingshou(chuKu);
        if (code <= 0) {
            throw new RuntimeException("保存失败，请检查数据重新尝试");
        }
        //批量插入子表
        JSONArray obj = JSONArray.parseArray(a);// 解析String 成JSONARRy
        List<ChuKuSon> chuKuSons = new ArrayList<>();
        double zongjia = 0;
        for (int i = 0; i < obj.size(); i++) {
            JSONObject jo = (JSONObject) obj.get(i);
            ChuKuSon chuKuSon = new ChuKuSon();
            chuKuSon.setId(UUIDUtil.getUUID());
            chuKuSon.setChukuId(chuKu.getId());
            chuKuSon.setDanjia(Double.parseDouble(jo.get("danjia").toString()));
            chuKuSon.setShuliang(Integer.parseInt(jo.get("shuliang").toString()));
            chuKuSon.setProductDetailsId(jo.get("productDetailsId").toString());
            chuKuSons.add(chuKuSon);
            zongjia += chuKuSon.getDanjia() * chuKuSon.getShuliang();
        }
        //批量插入子表
        code = ckDao.addChuKuSon(chuKuSons);
        if (code <= 0) {
            throw new RuntimeException("保存失败，请检查数据重新尝试");
        }
        //插入关系表
        Tuihuo tuihuo = new Tuihuo();
        tuihuo.setDanjuId(danjuId);
        tuihuo.setTuihuoId(chuKu.getId());
        tuihuo.setId(UUIDUtil.getUUID());
        code = tuihuoMapper.insert(tuihuo);
        if (code <= 0) {
            throw new RuntimeException("保存失败，请检查数据重新尝试");
        }

        // 判断是否是会员是会员就去查询余额，余额够就去更新余额，不够就去让他充值
        if ("-1".equals(chuKu.getWanglaidanwei()) || 0 == chuKu.getZhifu()) {//当为匿名或者会员现金支付时

        } else {//会员卡支付
            Vip vips = new Vip();
            vips.setId(chuKu.getWanglaidanwei());
            //新增消费记录
            vips.setCzmoney(zongjia);
            vips.setJifen((int) zongjia * -1);
            vips.setYue(zongjia * -1);
            vips.setLeixing(2);
            vips.setCreateBy(chuKu.getZhidanren());
            code = vipMapper.insertRecord(vips);
            vips.setBalance(zongjia);
            if (code < 0) {
                throw new MyException("操作失败，内部服务器错误");
            }
            //更新余额
            code = vipMapper.updateBlanceById(vips);
            if (code <= 0) {
                throw new MyException("操作失败，内部服务器错误");
            }
        }
        List<Store> stores = new ArrayList<>();
        //更新库存
        for (int i = 0; i < chuKuSons.size(); i++) {
            Store store = new Store();
            store.setShuliang(chuKuSons.get(i).getShuliang());
            store.setProductionDetailsId(chuKuSons.get(i).getProductDetailsId());
            store.setJgId(chuKu.getJgId());
            store.setLeixing(0);
            stores.add(store);
        }
        code = storeDao.updateShuliang(stores);
        if (code <= 0) {
            throw new MyException("操作失败，内部服务器错误");
        }
        //TODO 财务
        if (chuKu.getFenlei() == 1) {
            FinanceRecord recordRu = new FinanceRecord();
            recordRu.setAmount(Math.abs(zongjia)*-1);
            recordRu.setGsjg(chuKu.getJgId());
            recordRu.setWldw(chuKu.getWanglaidanwei());
            recordRu.setYddid(chuKu.getChukudanhao());
            recordRu.setFslx("零售退货");
            recordRu.setHl("" + (1));
            recordRu.setTime(new Date());
            recordRu.setWldwType(1);//销售为1；进货为0
            financeService.addFinanceRecord(recordRu);
        }

        return code;
    }

    @Override
    public Double findXiaoshou(User user) {
        Double zongjia;
        if (user != null) {
            zongjia = ckDao.findSaleXiaoshou(user.getJgid()) * -1;
        } else {
            throw new MyException("服务器连接已断开，请重新登录进行尝试");
        }
        return zongjia;
    }

    @Override
    public List<SaleXiaoPiao> findSaleXiaopiao(String id) {
        return ckDao.findSaleXiaopiao(id);
    }

    @Override
    public List<YearAndSeason> selectYearAndSeasaonSevice() {

        return ckDao.selectYearAndSeasaon();
    }

    /***
     * 出库报表
     * @param page
     * @return
     */
    @Override
    public List<ChuKuReport> selectChuKuReportList(PageBean page) {
        Map<String, Object> mapCan = new HashMap<>();
        mapCan.put("jgId", page.getJgId());
        mapCan.put("sort", page.getSort());
        mapCan.put("order", page.getOrder());
        mapCan.put("start", page.getStart());
        mapCan.put("pageSize", page.getRows());
        mapCan.put("key", page.getKey());
        mapCan.put("stime", page.getStime());
        mapCan.put("etime", page.getEtime());
        mapCan.put("type", page.getType());
        mapCan.put("chukuleixing", page.getChukuleixing());
        mapCan.put("wldwId", page.getWldwId());
        mapCan.put("year",page.getYear());
        mapCan.put("season",page.getSeason());
        mapCan.put("brand",page.getBrand());
        List<ChuKuReport> chukuReportList = ckDao.selectChuKuReportList(mapCan);
        Foot foot=ckDao.selectChuKuReportCount(mapCan);
        if(foot!=null){
            foot.setProduct("总计:");
        }
        page.setFoot(foot);
        return chukuReportList;
    }

    /***
     * 销售导出
     * @param page
     * @return
     */
    @Override
    public HSSFWorkbook selectChuKuReportListDaoChu(PageBean page) {

        Map<String, Object> mapCan = new HashMap<>();
        mapCan.put("jgId", page.getJgId());
        mapCan.put("sort", page.getSort());
        mapCan.put("order", page.getOrder());
        mapCan.put("key", page.getKey());
        mapCan.put("stime", page.getStime());
        mapCan.put("etime", page.getEtime());
        mapCan.put("type", page.getType());
        mapCan.put("chukuleixing", page.getChukuleixing());
        mapCan.put("wldwId", page.getWldwId());
        mapCan.put("year",page.getYear());
        mapCan.put("season",page.getSeason());
        mapCan.put("brand",page.getBrand());
        List<ChuKuReport> list = ckDao.selectChuKuReportListDaoChu(mapCan);
        int lie = 0;
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("sheet1");
        sheet.setColumnWidth(0, 20 * 256);
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();//
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("商品款号");
        cell = row.createCell(++lie);
        cell.setCellValue("品牌");
        cell = row.createCell(++lie);
        cell.setCellValue("年份");
        cell = row.createCell(++lie);
        cell.setCellValue("季节");
        cell = row.createCell(++lie);
        cell.setCellValue("大小童");
        cell = row.createCell(++lie);
        cell.setCellValue("大类");
        cell = row.createCell(++lie);
        if(page.getType()==1){
            cell.setCellValue("颜色");
            cell = row.createCell(++lie);
        }else if(page.getType()==2){
            cell.setCellValue("颜色");
            cell = row.createCell(++lie);
            cell.setCellValue("尺码");
            cell = row.createCell(++lie);
        }
        cell.setCellValue("净销量");
        cell = row.createCell(++lie);
        cell.setCellValue("金额");
        cell = row.createCell(++lie);
        sheet.setColumnWidth(lie, 10 * 800);

        for(int i=0;i<list.size();i++){
            lie=0;
            row = sheet.createRow(i + 1);
            row.createCell(lie).setCellValue(list.get(i).getProduct());
            row.createCell(++lie).setCellValue(list.get(i).getBrand());
            row.createCell(++lie).setCellValue(list.get(i).getYear());
            row.createCell(++lie).setCellValue(list.get(i).getSeason());
            row.createCell(++lie).setCellValue(list.get(i).getStyle());
            row.createCell(++lie).setCellValue(list.get(i).getDalei());
            if(page.getType()==1){
                row.createCell(++lie).setCellValue(list.get(i).getColor());
            }
             else if(page.getType()==2){
                row.createCell(++lie).setCellValue(list.get(i).getColor());
                row.createCell(++lie).setCellValue(list.get(i).getSize());
            }
            row.createCell(++lie).setCellValue(list.get(i).getZshuliang());
            row.createCell(++lie).setCellValue(list.get(i).getZongjia());
            cell = row.createCell(++lie);
            cell.setCellStyle(style);
        }

        return wb;
    }

    /***
     * 添加回执单图片
     * @param
     * @return
     */

    @Override
    public Integer addPicService(String chukuId,MultipartFile upfile,HttpSession session) {
             User u=(User)session.getAttribute("info");
             Map<String,Object> mapCan=new HashMap<>();
              mapCan.put("jgId", u.getJgid());
              mapCan.put("chukuId",chukuId);
             Integer chukuid = ckDao.selectOneChuKuDan(mapCan);
           if (chukuid != null ) {
                if(chukuid!=3){
                    throw new MyException("不是出库状态,不可添加回执单!");
                }
           }
        String fileName = upfile.getOriginalFilename();//获得图片名
        String contentType=upfile.getContentType();	//获取文件类型（后缀）
        //因为获取的后缀是XXXX/xxx形式
        contentType=contentType.substring(contentType.indexOf("/")+1);

        if(upfile==null || fileName=="" ){
                  throw new MyException("无图片!");
              }
                String newFileName =System.currentTimeMillis()+ UUIDUtil.getUUID()+"."+contentType;
        String root_path = session.getServletContext().getRealPath("upload");// 获取自定义缓存文件夹路径

        File file = new File(root_path);
        // 如果文件夹不存在，则创建
        if (!file.exists()) {

            file.mkdirs();
        }
        // 构建图片url路径，为显示图片做准备
       /* String url_root = session.getServletContext().getContextPath();*/

        String file_url = "/upload/" + newFileName;
        try {
            File file2 = new File(file, newFileName);
            upfile.transferTo(file2);// 将上传的文件移动到指定文件夹
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        mapCan.put("ren",u.getId());
        mapCan.put("time",new Date());
        mapCan.put("url",file_url);

        return ckDao.addPic(mapCan);
    }


}
